<template>
	<div class="app-container">
		<el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
			label-width="68px">
			<!-- <el-form-item label="资产领用唯一标识符" prop="id">
        <el-input
          v-model="queryParams.id"
          placeholder="请输入资产领用唯一标识符"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
			<el-form-item label="资产领用单号" prop="assetUsageNumber" label-width="100px">
				<el-input v-model="queryParams.assetUsageNumber" placeholder="请输入资产领用单号" clearable
					@keyup.enter.native="handleQuery" />
			</el-form-item>
			<!-- <el-form-item label="领用总数量" prop="totalQuantity">
        <el-input
          v-model="queryParams.totalQuantity"
          placeholder="请输入领用总数量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
			<el-form-item>
				<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
				<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
			</el-form-item>
		</el-form>

		<el-row :gutter="10" class="mb8">
			<el-col :span="1.5">
				<el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
					v-hasPermi="['system:usage:add']">新增</el-button>
			</el-col>
			<!--    <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:usage:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:usage:remove']"
        >删除</el-button>
      </el-col> -->
			<el-col :span="1.5">
				<el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
					v-hasPermi="['system:usage:export']">导出</el-button>
			</el-col>
			<right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
		</el-row>

		<el-table v-loading="loading" :data="usageList" @selection-change="handleSelectionChange">
			<el-table-column type="selection" width="55" align="center" />
			<!-- <el-table-column label="资产领用唯一标识符" align="center" prop="id" /> -->
			<el-table-column label="资产领用单号" align="center" prop="assetUsageNumber" />
			<el-table-column label="计划领用数" align="center" prop="totalQuantity" />
			<el-table-column label="已领用数" align="center" prop="receivedQuantity" />
			<el-table-column label="领用人" align="center" prop="cuserName" />
			<el-table-column label="备注" align="center" prop="remark" />
			<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
				<template slot-scope="scope">
					<el-button size="mini" type="text" icon="el-icon-view" @click="handleUpdate(scope.row)"
						v-hasPermi="['system:usage:edit']">查看</el-button>
					<el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
						v-hasPermi="['system:usage:remove']">删除</el-button>
					<!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:usage:remove']"
          >删除</el-button> -->
				</template>
			</el-table-column>
		</el-table>

		<pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
			@pagination="getList" />

		<!-- 添加或修改用于存储资产领用信息的对话框 -->
		<el-dialog :title="title" :visible.sync="open" width="80%" append-to-body :close-on-click-modal="false">
			<el-form ref="form" :model="form" :rules="rules" label-width="100px">
				<el-form-item label="资产领用单号" prop="assetUsageNumber">
					<el-input v-model="form.assetUsageNumber" placeholder="请输入资产领用单号" disabled />
				</el-form-item>
				<el-form-item label="领用总数量" prop="totalQuantity">
					<el-input v-model="form.totalQuantity" placeholder="请输入领用总数量" disabled />
				</el-form-item>
				<el-form-item label="领用人" prop="userName">
					<el-select v-model="form.userName" placeholder="请选择领用人" :disabled="!IsUpdate">
						<el-option v-for="item in UserList" :key="item.userId" :label="item.nickName"
							:value="item.userId">
						</el-option>
					</el-select>
					<!-- <el-input v-model="form.createBy" placeholder="请输入领用人" disabled /> -->
				</el-form-item>
				<!-- <el-form-item label="删除标志" prop="delFlag">
          <el-input v-model="form.delFlag" placeholder="请输入删除标志" disabled/>
        </el-form-item> -->
				<el-form-item label="备注" prop="remark">
					<el-input v-model="form.remark" type="textarea" placeholder="请输入内容" disabled />
				</el-form-item>
			</el-form>
			<!--明细表-->
			<div>
				<label>明细</label>
			</div>
			<div style="width: 100%; padding: 5px">
				<el-button @click="AddMingXi" type="primary" size="mini" icon="el-icon-plus"
					v-if="IsUpdate">新增</el-button>
			</div>
			<el-table border :data="InfoList" style="width: 100%" height="400">
				<!-- <el-table-column prop="id" label="序号" width="50" type="index" align="center" :index="index=>index+1" /> -->
				<el-table-column prop="rfidNumber" label="rfid编码" align="center">
					<template v-slot="scope">
						<span>{{ scope.row.rfidNumber }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="productName" label="资产名称" align="center">
					<template v-slot="scope">
						<span>{{ scope.row.productName }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="productNumber" label="资产编号" align="center">
					<template v-slot="scope">
						<span>{{ scope.row.productNumber }}</span>
					</template>
				</el-table-column>

				<el-table-column prop="productTypeIdName" label="资产类别" align="center">
					<template v-slot="scope">
						<span>{{ scope.row.productTypeIdName }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="warehouseIdNmae" label="领用仓库" align="center">
					<template v-slot="scope">
						<span>{{ scope.row.warehouseIdNmae }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="specificationModel" label="规格型号" align="center">
					<template v-slot="scope">
						<span>{{ scope.row.specificationModel }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="shelfLife" label="保质期" align="center">
					<template v-slot="scope">
						<span>{{ scope.row.shelfLife }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="remarks" label="备注" align="center">
					<template v-slot="scope">
						<span>{{ scope.row.remarks }}</span>
					</template>
				</el-table-column>
				<el-table-column label="资产状态" align="center" prop="productStatus">
					<template slot-scope="scope">
						<span style="color: #ff0000;" v-if="scope.row.productStatus=='未入库'">未入库</span>
						<span style="color: green;" v-if="scope.row.productStatus=='在库'">在库</span>
						<span style="color: orange;" v-if="scope.row.productStatus=='已领用'">已领用</span>
					</template>
				</el-table-column>
				<el-table-column label="发卡状态" align="center" prop="fkStatus">
					<template slot-scope="scope">
						<span style="color: #ff0000;" v-if="scope.row.fkStatus=='未发卡'">未发卡</span>
						<span style="color: green;" v-if="scope.row.fkStatus=='已发卡'">已发卡</span>
					</template>
				</el-table-column>
				<!-- <el-table-column label="盘点状态" align="center" prop="inventoryStatus">
	  		<template scope="scope">
	  			<span v-if="scope.row.inventoryStatus=='已盘点'" style="color:green">已盘</span>
	  			<span v-if="scope.row.inventoryStatus=='未盘点'" style="color: red">未盘</span>
	  		</template>
	  	</el-table-column> -->
				<el-table-column label="操作" width="50" align="center" v-if="IsUpdate">
					<template v-slot="scope">
						<div style="display: flex;">
							<el-button size="small" icon="Delete" type="text"
								@click="delVersion(scope.row,scope.$index)">删除
							</el-button>
						</div>
					</template>
				</el-table-column>
			</el-table>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitForm">确 定</el-button>
				<el-button @click="cancel">取 消</el-button>
			</div>
		</el-dialog>
		<!--  明细新增弹窗-->
		<el-dialog title="新增明细" :visible.sync="openMingXi" width="80%" append-to-body :close-on-click-modal="false">
      <el-form :model="queryParamsMingXi" ref="queryFormMingXi" size="small" :inline="true" v-show="showSearch"
               label-width="68px">
        <el-form-item label="资产类别" prop="productTypeId">
          <el-select v-model="queryParamsMingXi.productTypeId" placeholder="请选择资产类别">
            <el-option v-for="item in productTypeList" :key="item.id" :label="item.productTypeName"
                       :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="仓库" prop="warehouseId">
          <el-select v-model="queryParamsMingXi.warehouseId" placeholder="请选择仓库">
            <el-option v-for="item in warehouseList" :key="item.id" :label="item.warehouseName"
                       :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQueryMingXi">搜索
          </el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQueryMingXi">重置</el-button>
        </el-form-item>
      </el-form>
			<el-table v-loading="loading" :data="warehousingDetail" @selection-change="handleSelectionChangeMingXi"
				height="600" :row-key="getRowKey">
				<el-table-column type="selection" width="55" align="center" :reserve-selection="true"/>
				<el-table-column label="资产名称" align="center" prop="productName" />
				<el-table-column label="资产编号" align="center" prop="productNumber" />
				<el-table-column label="RFID编号" align="center" prop="rfidNumber" />
				<el-table-column label="资产类别" align="center" prop="productTypeIdName" />
				<el-table-column label="规格型号" align="center" prop="specificationModel" />
        <el-table-column label="所在仓库" align="center" prop="warehouseIdNmae" />
				<el-table-column label="保质期" align="center" prop="shelfLife" />
				<el-table-column label="备注" align="center" prop="remarks" />
				<el-table-column label="资产状态" align="center" prop="productStatus">
					<template slot-scope="scope">
						<span style="color: #ff0000;" v-if="scope.row.productStatus=='未入库'">未入库</span>
						<span style="color: green;" v-if="scope.row.productStatus=='在库'">在库</span>
						<span style="color: orange;" v-if="scope.row.productStatus=='已领用'">已领用</span>
					</template>
				</el-table-column>
				<el-table-column label="发卡状态" align="center" prop="fkStatus">
					<template slot-scope="scope">
						<span style="color: #ff0000;" v-if="scope.row.fkStatus=='未发卡'">未发卡</span>
						<span style="color: green;" v-if="scope.row.fkStatus=='已发卡'">已发卡</span>
					</template>
				</el-table-column>
			</el-table>
			<pagination v-show="totalMingXi>0" :total="totalMingXi" :page.sync="queryParamsMingXi.pageNum"
				:limit.sync="queryParamsMingXi.pageSize" @pagination="SelectMingXi" />
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitFormMingXi">确 定</el-button>
				<el-button @click="cancelMingXi">取 消</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	import {
		listUsage,
		getUsage,
		delUsage,
		addUsage,
		updateUsage,
		listProduct,
		listUser
	} from "@/api/system/usage";
  import { listType, listWarehouse } from '@/api/system/check'

	export default {
		name: "Usage",
		data() {
			return {
				// 遮罩层
				loading: true,
				// 选中数组
				ids: [],
				// 非单个禁用
				single: true,
				// 非多个禁用
				multiple: true,
				// 显示搜索条件
				showSearch: true,
				// 总条数
				total: 0,
				// 用于存储资产领用信息的表格数据
				usageList: [],
				// 弹出层标题
				title: "",
				// 是否显示弹出层
				open: false,
				// 查询参数
				queryParams: {
					pageNum: 1,
					pageSize: 10,
					id: null,
					assetUsageNumber: null,
					totalQuantity: null,
				},
				// 表单参数
				form: {},
				// 表单校验
				rules: {},
				// 入库明细数组
				InfoList: [],
				// 明细查询参数
				queryParamsMingXi: {
					pageNum: 1,
					pageSize: 15,
					productStatus: "在库",
					fkStatus: "已发卡",
          productTypeId:null,
          warehouseId:null
				},
				warehousingDetail: [],
				totalMingXi: 0,
				//选中的明细数据
				SelectInfoList: [],
				openMingXi: false,
				IsUpdate: false,
				// 仓库列表
				warehouseList: [],
				// 领用人列表
				UserList: [],
        productTypeList:[]
			};
		},
		created() {
			this.getList();
			// 获取领用人列表
			this.getlistUser();
      // 获取仓库列表
      this.listWarehouse();
      // 获取类别列表
      this.GetproductTypeList();
		},
		methods: {
      // 获取仓库列表
      listWarehouse() {
        listWarehouse().then(response => {
          console.log("仓库列表", response)
          this.warehouseList = response.rows;
        });
      },
      // 获取类别
      GetproductTypeList(){
        listType().then(response => {
          console.log("类别列表", response)
          this.productTypeList = response.rows;
        });
      },
			// 点击新增明细事件
			AddMingXi() {
				this.openMingXi = true;
				this.SelectMingXi();
			},
			/** 查询库存列表信息*/
			SelectMingXi() {
				console.log("99999999999")
				listProduct(this.queryParamsMingXi).then(response => {
					console.log(response);
					this.warehousingDetail = response.rows;
					this.totalMingXi = response.total;
				});
			},
			/** 查询用于存储资产领用信息的列表 */
			getList() {
				this.loading = true;
				listUsage(this.queryParams).then(response => {
					console.log("领用单列表", response)
					this.usageList = response.rows;
					this.total = response.total;
					this.loading = false;
				});
			},
			// 获取领用人列表
			getlistUser() {
				listUser().then(response => {
					console.log("领用人列表", response)
					this.UserList = response.rows;
				});
			},
			// 取消按钮
			cancel() {
				this.open = false;
				this.reset();
			},
			// 表单重置
			reset() {
				this.form = {
					id: null,
					assetUsageNumber: null,
					totalQuantity: null,
					delFlag: null,
					createBy: null,
					createTime: null,
					updateBy: null,
					updateTime: null,
					remark: null
				};
				this.resetForm("form");
			},
			/** 搜索按钮操作 */
			handleQuery() {
				this.queryParams.pageNum = 1;
				this.getList();
			},
			/** 重置按钮操作 */
			resetQuery() {
				this.resetForm("queryForm");
				this.handleQuery();
			},
			// 多选框选中数据
			handleSelectionChange(selection) {
				this.ids = selection.map(item => item.id)
				this.single = selection.length !== 1
				this.multiple = !selection.length
			},
			/** 新增按钮操作 */
			handleAdd() {
				this.reset();
				this.open = true;
				this.title = "创建领用申请单";
				this.InfoList = [];
				// 生成领用单单号
				this.form.assetUsageNumber = this.orderCode();
				this.IsUpdate = true;
				this.form.remark = "手持机领用";
			},
			/** 修改按钮操作 */
			handleUpdate(row) {
				this.reset();
				const id = row.id || this.ids
				this.IsUpdate = false;
				getUsage(id).then(response => {
					console.log("详情", response)
					this.form = response.data;
					this.InfoList = response.data.infoListS
					this.open = true;
					this.title = "查看资产领用信息";
				});
			},
			/** 提交按钮 */
			submitForm() {
				if (this.InfoList.length <= 0) {
					this.$message({
						showClose: true,
						message: '请添加需要领用的明细',
						type: 'warning'
					});
					return;
				}
				if (this.form.userName==null) {
					this.$message({
						showClose: true,
						message: '请选择领用人',
						type: 'warning'
					});
					return;
				}
				this.$confirm('请仔细复核领用信息，创建后将无法进行修改，确认创建此领用单？', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.$refs["form"].validate(valid => {
						if (valid) {
							if (this.form.id != null) {
								updateUsage(this.form, this.InfoList).then(response => {
									this.$modal.msgSuccess("修改成功");
									this.open = false;
									this.getList();
								});
							} else {
								addUsage(this.form, this.InfoList).then(response => {
									this.$modal.msgSuccess("新增成功");
									this.open = false;
									this.getList();
								});
							}
						}
					});
				});
			},
			/** 删除按钮操作 */
			handleDelete(row) {
				const ids = row.id || this.ids;
				this.$modal.confirm('是否确认删除领用单的编号为"' + ids + '"的数据项？').then(function() {
					return delUsage(ids);
				}).then(() => {
					this.getList();
					this.$modal.msgSuccess("删除成功");
				}).catch(() => {});
			},

			/** 导出按钮操作 */
			handleExport() {
				this.download('system/usage/export', {
					...this.queryParams
				}, `usage_${new Date().getTime()}.xlsx`)
			},
			//多选框选中明细数据
			handleSelectionChangeMingXi(selection) {
				console.log("选中的明细数据", selection)
				this.SelectInfoList = selection;
			},
			//确认明细数据
			submitFormMingXi() {
				this.InfoList = this.InfoList.concat(this.SelectInfoList);
				this.InfoList = this.unique(this.InfoList, 'rfidNumber');
				this.openMingXi = false;
				this.form.totalQuantity = this.InfoList.length
			},
			//明细取消按钮
			cancelMingXi() {
				this.openMingXi = false;
			},
			// 对象数组去重
			unique(arr, prop) {
				let obj = {};
				return arr.reduce(function(preValue, item) {
					obj[item[prop]] ? '' : obj[item[prop]] = true && preValue.push(item);
					return preValue
				}, [])

			},
			//删除明细数据
			delVersion(data, index) {
				console.log("删除的数据", data);
				console.log("删除的索引值", index)
				this.$confirm('是否删除此明细', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.InfoList.splice(index, 1);
					this.$message({
						type: 'success',
						message: '删除成功!'
					});
					this.form.totalQuantity = this.InfoList.length
				});

			},
			/**
			 * #JS生成订单号的函数
			 * @param
			 * @return string 生成的订单号
			 */
			orderCode() {
				const now = new Date();
				let month = now.getMonth() + 1;
				let day = now.getDate();
				let hour = now.getHours();
				let minutes = now.getMinutes();
				let seconds = now.getSeconds();
				// month = setTimeDateFmt(month);
				// day = setTimeDateFmt(day);
				// hour = setTimeDateFmt(hour);
				// minutes = setTimeDateFmt(minutes);
				// seconds = setTimeDateFmt(seconds);
				let orderCode = now.getFullYear().toString() + month.toString() + day + hour + minutes + seconds;
				return orderCode;
			},
      getRowKey (row) {
        return row.id
      },
      // 搜索明细
      handleQueryMingXi() {
        this.queryParamsMingXi.pageNum = 1;
        this.SelectMingXi();
      },
      //重置明细搜索
      resetQueryMingXi() {
        this.resetForm("queryFormMingXi");
        this.handleQueryMingXi();
      },
		}
	};
</script>
